package com.atguigu.ware.listener;

import com.atguigu.common.to.StockLockedTo;
import com.atguigu.common.vo.OrderVo;
import com.atguigu.ware.service.WareSkuService;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * description: StockRealseListener
 * date: 2022/12/29 19:23
 * author: MR.孙
 */
@Slf4j
@Component
@RabbitListener(queues = {"stock.release.stock.queue"})
public class StockRealseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        log.info("************************从订单服务收到库存解锁的消息********************************");
        try {
            wareSkuService.unLock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     *存在问题：由于机器卡顿、消息延迟等导致关单消息未延迟发送，解锁库存消息正常发送和监听，导致解锁库存消息被消费，当执行完关单操作后便无法再执行解锁库存操作，导致卡顿的订单永远无法解锁库存。
     *解决方案：采取主动补偿的策略。当关单操作正常完成之后，主动去发送解锁库存消息给MQ，监听解锁库存消息进行解锁。
     * @return
     */
    @RabbitHandler
    public void handleStockRelease(OrderVo orderVo, Message message, Channel channel) throws IOException {
        log.info("************************从订单服务收到库存解锁的消息********************************");
        try {
            wareSkuService.unLock(orderVo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

}
